package com.ktjy.service.impl;

import com.ktjy.service.IUploadService;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.UUID;

@Service
public class UploadServiceImpl implements IUploadService {
    @Value("${minio.endpoint}")
    String endpoint;
    @Value("${minio.accessKey}")
    String accessKey;
    @Value("${minio.secretKey}")
    String secretKey;
    @Value("${minio.bucket}")
    String bucket;

    public String upload(MultipartFile file) throws Exception {
        //根minio服务建立一个连接
        MinioClient minioClient =
                MinioClient.builder()
                        .endpoint(endpoint)
                        .credentials(accessKey, secretKey)
                        .build();
        //判断桶是否存在
        boolean found =
                minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build());
        if (!found) {//如果桶不存在
            //创建桶
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build());
        }
        //首先获取文件原名
        String originalFilename = file.getOriginalFilename();
        //获取后缀
        String suffix =  StringUtils.getFilenameExtension(originalFilename);
        //拼接新的文件名
        String fileName = UUID.randomUUID() + "." + suffix;
        //上传文件流
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucket)
                        .object(fileName)
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build());
        return bucket + "/" + fileName;
    }
}
